package com.hudongwx.godoffood.fragment;


import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.LoginActivity;
import com.hudongwx.godoffood.activity.home_activity.SearchActivity;
import com.hudongwx.godoffood.activity.myActivity.CommunityMsgActivity;
import com.hudongwx.godoffood.fragment.Adapter.MyGridViewAdapter;
import com.hudongwx.godoffood.fragment.Adapter.MyListViewAdapter;
import com.hudongwx.godoffood.fragment.Adapter.MyListViewAdapter2;
import com.hudongwx.godoffood.fragment.Adapter.MyViewpagerAdapter;
import com.hudongwx.godoffood.fragment.Handler.MyHandler;
import com.hudongwx.godoffood.resfRecycle.MyRecyclerView;
import com.hudongwx.godoffood.utils.API.API;
import com.hudongwx.godoffood.utils.MyApplication;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

@ContentView(R.layout.fragment_home)
public class HomeFragment extends Fragment {
    private String TAG="HomeFragment";
    private View view=null;
    private List<ImageView> imgList;
    JSONArray pageImgData,foodMenuData,communityData,specialData;
    @ViewInject(R.id.home_recycler_view)
    RecyclerView recyclerView;
    int p=0;//标记变量，用于记录接收消息状态
    private Handler handler;
    public MyHandler mHandler;

    private RecyclerViewAdapter adapter;
//    @ViewInject(R.id.home_refresh)
//    SwipeRefreshLayout refreshLayout;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null == view){
            view = x.view().inject(this, inflater, container);
            loadViewPagerImg();
            loadMenuData();
            loadCommunityData();
            loadSpecialData();

            handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    int what=msg.what;
                    switch (what){
                        case 0:
                            p++;
                            break;
                        case 1:
                            p++;
                            break;
                        case 2:
                            p++;
                            break;
                        case 3:
                            p++;
                            break;
//                        case 4:
//                            adapter.refresh(pageImgData,foodMenuData,communityData,specialData);
//                            refreshLayout.setRefreshing(false);
//                            break;
                    }
//                    if (p==4&&adapter!=null){
//                        handler.sendEmptyMessage(4);
//                        p=0;
//                    }
                    //如果四条条消息都接收到了，就设置适配器传值
                    if (p==4&&pageImgData!=null&&foodMenuData!=null&&communityData!=null&&specialData!=null){
                        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 1);
                        recyclerView.setLayoutManager(gridLayoutManager);
                        //设置recyclerview的item之间的间距
                        recyclerView.addItemDecoration(new SpaceItemDecoration(20));
                        adapter = new RecyclerViewAdapter(pageImgData, foodMenuData, communityData, specialData);
                        recyclerView.setAdapter(adapter);
                        p=0;
//                        //刷新页面设置
//                        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//                            @Override
//                            public void onRefresh() {
//                                Log.i(TAG, "handleMessageaaaa:999 ");
//                                loadViewPagerImg();
//                                loadMenuData();
//                                loadSpecialData();
//                                loadCommunityData();
//
//                            }
//                        });
                    }

                }
            };

        }
        return view;
    }

    /**
     * 加载头部的轮播viewpager
     */
    public void loadViewPagerImg(){

        RequestParams params = new RequestParams(API.getViewPagerImg());
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONArray data = result.getJSONArray("Data");
                    pageImgData = data;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                Message message = handler.obtainMessage();
                message.what = 0;
                handler.sendMessage(message);
            }
        });
    }

    /**
     * 加载食品分类菜单
     */
    public void loadMenuData(){
        RequestParams params = new RequestParams(API.getFoodMenu());
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONArray data = result.getJSONArray("Data");
                    foodMenuData = data;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onSuccess: "+foodMenuData.length());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                //数据加载完成后通过handler发送一条消息
                Message message = handler.obtainMessage();
                message.what=1;
                handler.sendMessage(message);
            }
        });
    }

    /**
     * 加载社区热帖数据
     */
    public void loadCommunityData(){
        RequestParams params = new RequestParams(API.getCommunity());
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONArray data = result.getJSONArray("Data");
                    communityData = data;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onSuccess: "+result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                //数据加载完成后通过handler发送一条消息
                Message message = handler.obtainMessage();
                message.what=2;
                handler.sendMessage(message);
            }
        });
    }

    /**
     * 加载精选专题数据
     */
    public void loadSpecialData(){
        RequestParams params = new RequestParams(API.getSpecial());
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONArray data = result.getJSONArray("Data");
                    specialData = data;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onSuccess: "+result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                //数据加载完成后通过handler发送一条消息
                Message message = handler.obtainMessage();
                message.what=3;
                handler.sendMessage(message);
            }
        });
    }


    class RecyclerViewAdapter extends RecyclerView.Adapter<MyViewHolder>{
        JSONArray pageImgData,foodMenuData,communityData,specialData;

        public RecyclerViewAdapter(JSONArray pageImgData, JSONArray foodMenuData,
                                   JSONArray communityData, JSONArray specialData) {
            this.pageImgData = pageImgData;
            this.foodMenuData = foodMenuData;
            this.communityData = communityData;
            this.specialData = specialData;
        }

//        public void refresh(JSONArray pageImgData, JSONArray foodMenuData,
//                            JSONArray communityData, JSONArray specialData){
//            this.pageImgData = pageImgData;
//
//            this.foodMenuData = foodMenuData;
//            this.communityData = communityData;
//            this.specialData = specialData;
//            notifyDataSetChanged();
//        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType==0){
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.pager_view, null);
                return new MyViewHolder(view);
            } else if (viewType == 1){
                //食品分类
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.food_menu, null);
                return new MyViewHolder(view);
            }else if (viewType == 2){
                //社区热帖
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.community_blogs, null);
                return new MyViewHolder(view);
            }else {
                //精选专题
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.special_select, null);
                return new MyViewHolder(view);
            }
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            Log.i(TAG, "onBindViewHolder: viewpager"+position);
            LinearLayout.LayoutParams params;
            if (0==position){
                ViewPagerClickListener listener= new ViewPagerClickListener(holder);
                mHandler = new MyHandler(new WeakReference(HomeFragment.this),holder);
                //给viewpager添加监听事件
                holder.viewPager.addOnPageChangeListener(listener);
                //用于存放网络解析出来的图片
                List<ImageView> imgList = new ArrayList<>();
                int len = pageImgData.length();
                for (int i = 0; i < len; i++) {
                    try {
                        String url = pageImgData.getJSONObject(i).getString("Url");
                        ImageView img = new ImageView(getActivity());
                        x.image().bind(img,url);
                        imgList.add(img);

                        //设置三个标记点
                        params = new LinearLayout.LayoutParams(20,20);
                        params.setMargins(10,0,10,0);
                        View sign = new View(getActivity());
                        sign.setLayoutParams(params);
                        sign.setBackgroundResource(R.drawable.shape_sign_img);
                        sign.setSelected(false);
                        holder.linearLayout.addView(sign);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                holder.viewPager.setAdapter(new MyViewpagerAdapter(pageImgData,imgList,getActivity()));
                //设置一个很大值的中间值
                holder.viewPager.setCurrentItem(Integer.MAX_VALUE/2);
                //开始轮播
                mHandler.sendEmptyMessageDelayed(MyHandler.MSG_UPDATE_IMAGE,MyHandler.MSG_DELAY);
            } else if (1==position){
                //食品分类的gridview设置adapter
                Log.i(TAG, "onBindViewHolder: "+foodMenuData.length());
                holder.gridView.setAdapter(new MyGridViewAdapter(foodMenuData,getActivity()));
            } else if (2==position){
                //社区热帖的listview设置adapter
                Log.i(TAG, "onBindViewHolder: "+communityData.length());
                holder.listView.setAdapter(new MyListViewAdapter(communityData,getActivity()));
            }else {
                //精选专题的listview设置adapter
                holder.listView2.setAdapter(new MyListViewAdapter2(specialData,getActivity()));
            }
        }

        @Override
        public int getItemCount() {
            return 4;
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }
    }

    //viewpager的点击事件
    class ViewPagerClickListener implements ViewPager.OnPageChangeListener {
        MyViewHolder holder;

        public ViewPagerClickListener(MyViewHolder holder) {
            this.holder = holder;
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            mHandler.sendMessage(Message.obtain(mHandler,MyHandler.MSG_PAGE_CHANGED,position,0));
            int num = position%3;
            int count = holder.linearLayout.getChildCount();
            for (int i = 0; i < count; i++) {
                if (i==num){
                    holder.linearLayout.getChildAt(i).setSelected(true);
                }else {
                    holder.linearLayout.getChildAt(i).setSelected(false);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            switch (state){
                //滑动完成
                case ViewPager.SCROLL_STATE_SETTLING:
                    mHandler.sendEmptyMessageDelayed(MyHandler.MSG_UPDATE_IMAGE,MyHandler.MSG_DELAY);
                    break;
                //正在滑动
                case ViewPager.SCROLL_STATE_DRAGGING:
                    Log.i(TAG, "onPageScrollStateChanged: "+state);
                    mHandler.sendEmptyMessage(MyHandler.MSG_KEEP_SILENT);
                    break;
                default:
                    break;
            }
        }
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        private LinearLayout linearLayout;
        private ViewPager viewPager;
        private GridView gridView;
        private ListView listView,listView2;

        public MyViewHolder(View itemView) {
            super(itemView);
            this.linearLayout = (LinearLayout) itemView.findViewById(R.id.view_pager_guide);
            this.viewPager = (ViewPager) itemView.findViewById(R.id.view_pager);
            this.gridView = (GridView) itemView.findViewById(R.id.food_menu_grid);
            this.listView = (ListView) itemView.findViewById(R.id.community_blogs_list);
            this.listView2 = (ListView) itemView.findViewById(R.id.special_select_list);
        }

        public ViewPager getViewPager() {
            return viewPager;
        }

        public void setViewPager(ViewPager viewPager) {
            this.viewPager = viewPager;
        }
    }

    //设置recyclerview的item之间的间距
    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
//            outRect.left = space;
//            outRect.right = space;
            outRect.bottom = space;

            // Add top margin only for the first item to avoid double space between items
//            if(parent.getChildPosition(view) == 0)
//                outRect.top = space;
        }

    }

    //跳转搜索页面
    @Event(R.id.home_tosearch)
    private void toSearch(View view ){
        Intent intent = new Intent(getActivity(), SearchActivity.class);
        startActivity(intent);
    }

    //跳转社区
    @Event(R.id.home_tocommunity)
    private void toCommunity(View view){
        String uid = MyApplication.getStorage("Uid");
        if (!uid.equals("1")){
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }else {
            startActivity(new Intent(getActivity(), CommunityMsgActivity.class));
        }

    }
}
